package com.promise.jokerdream.ui.timer

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import com.promise.jokerdream.database.entity.TimerTaskConfigEntity
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.ui.components.TaskNameInputDialog
import com.promise.jokerdream.ui.components.TimePickerDialog
import com.promise.jokerdream.ui.components.SelectionRow
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar

/**
 * 定时任务配置页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimerTaskConfigPage(
    userId: String,
    taskId: String,
    onBackClick: () -> Unit,
    onNavigateToExecutionLog: () -> Unit
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    
    // 处理返回手势
    BackHandler {
        onBackClick()
    }
    
    // 定时任务配置状态
    var timerTaskConfig by remember { mutableStateOf<TimerTaskConfigEntity?>(null) }
    
    // 编辑对话框状态
    var showEditDialog by remember { mutableStateOf(false) }
    var editingTask by remember { mutableStateOf<TimerTaskConfigEntity?>(null) }
    
    // 时间选择器状态
    var showStartTimePicker by remember { mutableStateOf(false) }
    var showEndTimePicker by remember { mutableStateOf(false) }
    
    // 加载现有任务数据
    LaunchedEffect(userId, taskId) {
        val account = userDataManager.getUserAccount(userId)
        val existingTask = account?.config?.timerTaskConfig?.find { it.taskId == taskId }
        timerTaskConfig = existingTask
    }
    
    // 同步定时任务到数据库的函数
    fun syncTimerTaskToUserConfig(
        userDataManager: UserDataManager,
        userId: String,
        updatedTask: TimerTaskConfigEntity
    ) {
        kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) {
            try {
                userDataManager.updateTimerTask(userId, updatedTask)
                // 更新本地状态
                timerTaskConfig = updatedTask
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        // 顶部导航栏
        AppTopBar(
            title = timerTaskConfig?.taskName ?: "定时任务配置",
            onBackClick = onBackClick,
            actionIcon = {
                if (timerTaskConfig != null) {
                    Button(
                        onClick = { 
                            editingTask = timerTaskConfig
                            showEditDialog = true 
                        },
                        modifier = Modifier.height(28.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary
                        ),
                        contentPadding = PaddingValues(horizontal = AppSpacing.componentLarge)
                    ) {
                        Text(
                            text = "编辑",
                            fontSize = AppFontSizes.buttonMedium,
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
            }
        )
        
        // 内容区域
        if (timerTaskConfig == null) {
            // 加载中或未找到状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "定时任务不存在",
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        } else {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                LazyColumn(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = AppSpacing.pageHorizontal),
                    verticalArrangement = Arrangement.spacedBy(0.dp),
                    contentPadding = PaddingValues(vertical = AppSpacing.pageVertical)
                ) {
                    item {
                        TimeConfigSection(
                            startTime = timerTaskConfig!!.startTime,
                            endTime = timerTaskConfig!!.endTime,
                            onStartTimeClick = { 
                                // 开始时间选择
                                showStartTimePicker = true
                            },
                            onEndTimeClick = { 
                                // 结束时间选择
                                showEndTimePicker = true
                            }
                        )
                    }
                }
            }
        }
    }
    
    // 编辑对话框
    TaskNameInputDialog(
        show = showEditDialog,
        initialText = editingTask?.taskName ?: "",
        onTaskNameEntered = { taskName ->
            val updatedTask = editingTask!!.copy(
                taskName = taskName
            )
            
            // 保存到数据库
            syncTimerTaskToUserConfig(userDataManager, userId, updatedTask)
            
            showEditDialog = false
            editingTask = null
        },
        onDismiss = {
            showEditDialog = false
            editingTask = null
        }
    )
    
    // 开始时间选择器
    if (showStartTimePicker) {
        TimePickerDialog(
            show = showStartTimePicker,
            onTimeSelected = { time ->
                val updatedTask = timerTaskConfig!!.copy(startTime = time)
                timerTaskConfig = updatedTask
                syncTimerTaskToUserConfig(userDataManager, userId, updatedTask)
                showStartTimePicker = false
            },
            onDismiss = { showStartTimePicker = false },
            selectedTime = timerTaskConfig?.startTime ?: "09:00",
            description = "选择开始时间"
        )
    }
    
    // 结束时间选择器
    if (showEndTimePicker) {
        TimePickerDialog(
            show = showEndTimePicker,
            onTimeSelected = { time ->
                val updatedTask = timerTaskConfig!!.copy(endTime = time)
                timerTaskConfig = updatedTask
                syncTimerTaskToUserConfig(userDataManager, userId, updatedTask)
                showEndTimePicker = false
            },
            onDismiss = { showEndTimePicker = false },
            selectedTime = timerTaskConfig?.endTime ?: "10:00",
            description = "选择结束时间"
        )
    }
}

/**
 * 时间配置区域
 */
@Composable
private fun TimeConfigSection(
    startTime: String,
    endTime: String,
    onStartTimeClick: () -> Unit,
    onEndTimeClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Column(
            modifier = Modifier.padding(AppSpacing.componentLarge),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = "时间设置",
                fontSize = AppFontSizes.mediumBody,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            // 开始时间
            SelectionRow(
                label = "开始时间：",
                selectedText = startTime,
                onClick = onStartTimeClick
            )
            
            // 结束时间
            SelectionRow(
                label = "结束时间：",
                selectedText = endTime,
                onClick = onEndTimeClick
            )
        }
    }
}

